// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async event => {
  const {
    type,
    screenId,
    startDate,
    endDate,
    limit = 100,
    skip = 0,
    field = 'date',
    order = 'desc',
  } = event
  const collection = `${type}-cast`

  const where = {
    screenId,
    date: _.and(
      startDate ? _.gte(startDate) : _.neq(null),
      endDate ? _.lte(endDate) : _.neq(null)
    ),
  }

  const { total } = await db.collection(collection).where(where).count()

  const { data } = await db
    .collection(collection)
    .where(where)
    .orderBy(field, order)
    .limit(limit)
    .skip(skip)
    .get()

  return { total, items: data }
}
